<template>
  <div class="dashboard-container">
    <div class="app-container">
      <!-- 靠右的按钮 -->
      <page-tools>
        <template v-slot:after>
          <el-button type="primary" size="small" @click="addPermission('0', 1)">添加权限</el-button>
        </template>
      </page-tools>
      <!-- 表格 -->
      <el-table border :data="list" row-key="id" default-expand-all :row-class-name="rowClassName">
        <el-table-column label="名称" prop="name" />
        <el-table-column align="center" label="标识" prop="code" />
        <el-table-column align="center" label="描述" prop="description" />
        <el-table-column align="center" label="操作">
          <template slot-scope="{ row }">
            <el-button v-if="row.type === 1" type="text" @click="addPermission(row.id, 2)">添加权限点</el-button>
            <el-button type="text" @click="editPermission(row.id)">编辑权限点</el-button>
            <el-button type="text" @click="delPermission(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 添加子权限 -->
    <edit-permission ref="editPermissionRef" @get-permission="getPermissionList" />
  </div>
</template>

<script>
import { delPermission, getPermissionList } from '@/api/permission'
import { _noLimitCate } from '@/utils'
import EditPermission from './components/edit-permission.vue'
export default {
  components: {
    EditPermission
  },
  data() {
    return {
      // 权限列表: type:1代表页面权限、2代表按钮权限、3代表api权限
      list: []
    }
  },
  created() {
    this.getPermissionList()
  },
  methods: {
    async getPermissionList() {
      // 将数据转换为树形数据
      const res = await getPermissionList()
      // console.log(res)
      this.list = _noLimitCate(res, '0')
    },
    // 返回行的样式的类名
    rowClassName({ row }) {
      // console.log(row) // row是每一行的数据
      if (row.type === 2) {
        return 'icon-hide'
      } else if (row.type === 3) {
        return 'hide'
      } else {
        return ''
      }
    },
    // 删除权限
    async delPermission(row) {
      try {
        await this.$confirm('您确定要删除该权限吗')
        // 如果该权限下还有子权限，不允许删除
        if (row.children && row.children.length > 0) {
          this.$message.warning('该权限下还有子权限')
          return
        }
        await delPermission(row.id)
        this.$message.success('删除成功')
        this.getPermissionList()
      } catch (err) {
        this.$message.error('暂无操作权限')
      }
    },
    // 打开添加权限的对话框
    addPermission(pid, type) {
      this.$refs.editPermissionRef.open({ pid, type })
    },
    // 打开添加权限的对话框
    editPermission(id) {
      this.$refs.editPermissionRef.open({ id })
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep {
  // 这是控制三级权限行的隐藏的样式
  .hide {
    display: none;
  }
  // 控制二级权限左边箭头图标的样式
  .icon-hide {
    .el-table__expand-icon {
      opacity: 0;
    }
  }
}
</style>
